package com.sdkj.dspservice.modules.report.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdkj.dspservice.common.base.service.impl.CrudServiceImpl;
import com.sdkj.dspservice.common.utils.CollectionsUtils;
import com.sdkj.dspservice.modules.report.dao.TableConfigColumnDao;
import com.sdkj.dspservice.modules.report.dao.TableConfigDao;
import com.sdkj.dspservice.modules.report.entity.TableConfig;
import com.sdkj.dspservice.modules.report.entity.TableConfigColumn;
import com.sdkj.dspservice.modules.report.service.TableConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 表配置service实现类
 *
 * @author tm
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class TableConfigServiceImpl extends CrudServiceImpl<TableConfigDao, TableConfig> implements TableConfigService {

    @Autowired
    private TableConfigColumnDao tableConfigColumnDao;

    @Transactional(readOnly = false)
    @Override
    public boolean saveOrUpdate(TableConfig tableConfig) {
        boolean isNewRecord = tableConfig.isNewRecord();
        boolean result = super.saveOrUpdate(tableConfig);
        // 如果是更新，则需要把之前的字段列表删除
        if (!isNewRecord) {
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("table_config_id", tableConfig.getId());
            List<TableConfigColumn> oldTableConfigColumnList = tableConfigColumnDao.selectList(queryWrapper);
            if(CollectionsUtils.isNotEmpty(oldTableConfigColumnList)){
                tableConfigColumnDao.deleteBatchIds(oldTableConfigColumnList.stream().map(TableConfigColumn::getId).collect(Collectors.toList()));
            }
        }
        // 插入
        for (TableConfigColumn tableConfigColumn : tableConfig.getColumnList()) {
            tableConfigColumn.setTableConfigId(tableConfig.getId());
            tableConfigColumnDao.insert(tableConfigColumn);
        }
        return result;
    }
}

